<script lang="ts" setup>
  import { ref } from 'vue';
  import { Form, Message } from '@arco-design/web-vue';
  import { createGameEnrollType, updateGameEnrollType } from '@/api/game';
  import { GameEnrollType } from '@/types/game';

  const props = defineProps<{
    gameId: string;
    record?: GameEnrollType;
  }>();

  const emit = defineEmits(['close']);

  const data = ref<{
    name: string;
  }>({
    name: props.record ? props.record.name : '',
  });

  const formRef = ref<InstanceType<typeof Form> | null>(null);

  const saving = ref(false);
  const handleSubmit = async () => {
    if (formRef.value) {
      const validate = await formRef.value.validate();
      if (!validate) {
        try {
          saving.value = true;
          if (props.record) {
            await updateGameEnrollType({
              ...props.record,
              ...data.value,
            });
          } else {
            await createGameEnrollType({
              gameId: props.gameId,
              ...data.value,
            });
          }
          Message.success('操作成功');
          emit('close', true);
        } finally {
          saving.value = false;
        }
      }
    }
  };
</script>

<template>
  <a-modal
    :title="record ? '修改组别' : '添加组别'"
    :width="400"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <div class="editor">
      <a-form ref="formRef" :model="data" layout="vertical">
        <a-form-item
          label="组别"
          field="name"
          :rules="[{ required: true, message: '请输入组别名称' }]"
        >
          <a-input v-model="data.name" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>
